// src/gpu/ResourceRecord.js
/**
 * ResourceRecord
 * 表示一个托管在 GpuResourceManager 中的 GPU 资源对象
 * 提供生命周期控制和调试辅助。
 */

export class ResourceRecord {
  /**
   * @param {WebGLRenderingContext} gl
   * @param {WebGLObject} glObject - WebGL 对象
   * @param {'texture'|'buffer'|'framebuffer'} type
   * @param {number} byteSize - 估算的显存字节数
   * @param {string} [name] - 可选调试名
   */
  constructor(gl, glObject, type, byteSize, name = '') {
    this.gl = gl;
    this.glObject = glObject;
    this.type = type;
    this.byteSize = byteSize;
    this.name = name;

    // 状态字段
    this.createdAt = performance.now();
    this.lastUsed = this.createdAt;
    this.destroyed = false;

    // 可选调试堆栈
    if (process.env.NODE_ENV !== 'production') {
      this.stackTrace = new Error().stack;
    }
  }

  /** 标记资源被使用 */
  markUsed() {
    this.lastUsed = performance.now();
  }

  /** 判断资源是否超时未使用 */
  isExpired(maxAgeMs) {
    return (performance.now() - this.lastUsed) > maxAgeMs;
  }

  /** 销毁 GPU 对象 */
  destroy() {
    if (this.destroyed) return;
    const gl = this.gl;

    try {
      switch (this.type) {
        case 'texture':
          gl.deleteTexture(this.glObject);
          break;
        case 'buffer':
          gl.deleteBuffer(this.glObject);
          break;
        case 'framebuffer':
          gl.deleteFramebuffer(this.glObject);
          break;
        default:
          console.warn(`[ResourceRecord] Unknown type: ${this.type}`);
      }
    } catch (e) {
      console.warn('[ResourceRecord] Failed to delete resource:', e);
    }

    this.destroyed = true;
    this.glObject = null;
  }

  /** 获取调试信息 */
  getInfo() {
    const age = ((performance.now() - this.lastUsed) / 1000).toFixed(2);
    return {
      name: this.name,
      type: this.type,
      sizeMB: (this.byteSize / 1024 / 1024).toFixed(2) + ' MB',
      lastUsed: age + 's ago',
      destroyed: this.destroyed,
    };
  }
}
